#!/usr/bin/perl

#************************************************************
# Spawns a number of files of arbitrary sizes named randomly
#************************************************************

use strict;
use warnings;

use constant BUFF_AT_ONCE => 1048576;

if (@ARGV < 3 || @ARGV > 4) {
	print STDERR "Usage: $0 <path> <numfiles> [<size_min>] <size_max>\n";
	exit 1;
}

my $pathto = $ARGV[0];
my $numfiles = $ARGV[1];
my $minsize = (@ARGV == 3) ? 0 : $ARGV[2];
my $maxsize = (@ARGV == 3) ? $ARGV[2] : $ARGV[3];

if (!(-w $pathto)) {
	print STDERR "Couldn't access output path $pathto\n";
	exit 1;
}

if ($minsize < 0) {
	print STDERR "Bad size floor: $minsize\n";
	exit 1;
}

if ($maxsize < 0) {
	print STDERR "Bad size ceiling: $maxsize\n";
	exit 1;
}

if ($maxsize < $minsize) {
	print STDERR "Bad size constraint\n";
	exit 1;
}

my @rubbish;
my $count = $maxsize;

if ($count > BUFF_AT_ONCE) {
	$count = BUFF_AT_ONCE;
}

srand;

while ($count--) {
	push (@rubbish, pack('C', int rand 256));
}

my @salt = ('.', 0..9, 'A'..'Z', 'a'..'z');
my $filesize;
my $filename;
my $dsize;

$dsize = $maxsize - $minsize;

for ($count = 0; $count < $numfiles; $count++) {
	$filesize = $minsize + (($dsize > 0) ? int rand ($dsize + 1) : 0);
	$filename = join '', (@salt)[rand @salt, rand @salt, rand @salt, rand @salt, rand @salt, rand @salt];
	if (open OUTFILE, ">$pathto/$filename") {
		if ($filesize) { # can be zero as well
			binmode OUTFILE;
			while ($filesize > BUFF_AT_ONCE) {
				print OUTFILE @rubbish;
				$filesize -= BUFF_AT_ONCE;
			}
			print OUTFILE @rubbish[0..$filesize - 1];
		}
		close OUTFILE;
	}
}

0;
